/**
 * Author:yuiop
 * Date:2022/11/8 16:31
 */
package com.devops.admin.util;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class WebhookUtil {
    /**
     * 处理webhook链接
     * @param webhook
     * @param secret
     * @return
     * @throws Exception
     */
    public static String dealWebHook(String webhook,String secret) throws Exception {
        if (StrUtil.isBlank(secret)) {
            return webhook;
        }
        Long timestamp = System.currentTimeMillis();

        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        return webhook + "&timestamp=" + timestamp + "&sign=" + sign;
    }
}
